#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry

import sys
import os
import logging
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    # import pymel.core as pm
    import maya.mel as mel
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class UnKnownNode(CheckBase):
    def __init__(self):
        super(UnKnownNode, self).__init__()
        pass

    def unknown_node(self, fix=False):
        unknown_nodes = cmds.ls(type='unknown') or []
        unknowndag_nodes = cmds.ls(type='unknownDag') or []
        unknown_nodes.extend(unknowndag_nodes)
        no_fix = []
        if unknown_nodes and fix:
            for node in unknown_nodes:
                try:
                    cmds.lockNode(node, l=False)
                    cmds.delete(node)
                except Exception as e:
                    log.warning(e)
                    no_fix.append(node)
            return no_fix
        return unknown_nodes

    def check(self):
        unknown_node = self.unknown_node()
        if unknown_node:
            result_log = u'Error:%s\n' % unknown_node
        else:
            result_log = u'Succeed:没有问题\n'
        return result_log

    def fix(self):
        result_proc = self.unknown_node()
        if result_proc:
            try:
                import maya.mel as mel
                script = 'C:/Program Files/Autodesk/Maya2018/scripts/startup/cleanUpScene.mel'
                mel.eval("""source "%s";""" % script)

                result_fix = self.unknown_node(fix=True)
                if result_fix:
                    log.warning('have no fix {}'.format(result_fix))
                # Delete unknown nodes
                mel.eval('deleteUnknownNodes')
                # Delete unused expressions
                mel.eval('deleteUnusedExpressions')
                # Delete unused sets
                mel.eval('deleteUnusedSets')
                # Delete empty transforms
                mel.eval('deleteEmptyGroups')
                # Delete empty display layers
                mel.eval('deleteEmptyLayers("Display")')
                # Delete empty render layers
                mel.eval('deleteEmptyLayers("Render")')
                # Delete unused sets
                mel.eval('deleteUnusedSets')
                # Delete unused groupId nodes
                mel.eval('deleteUnusedCommon(\"groupId\", 0, 0)')
                result_log = u'Succeed:%s已经删除\n' % result_proc
                return result_log
            except:
                try:
                    import maya.mel as mel
                    script = 'C:/Program Files/Autodesk/Maya2018/scripts/startup/cleanUpScene.mel'
                    mel.eval("""source "%s";""" % script)

                    self.unknown_node(fix=True)
                    # Delete unknown nodes
                    mel.eval('deleteUnknownNodes')
                    # Delete unused expressions
                    mel.eval('deleteUnusedExpressions')
                    # Delete unused sets
                    mel.eval('deleteUnusedSets')
                    # Delete empty transforms
                    mel.eval('deleteEmptyGroups')
                    # Delete empty display layers
                    mel.eval('deleteEmptyLayers("Display")')
                    # Delete empty render layers
                    mel.eval('deleteEmptyLayers("Render")')
                    # Delete unused sets
                    mel.eval('deleteUnusedSets')
                    # Delete unused groupId nodes
                    mel.eval('deleteUnusedCommon(\"groupId\", 0, 0)')
                    result_log = u'Succeed:%s已经删除\n' % result_proc
                    return result_log
                except:
                    return u'Error:%s没有删除成功\n' % result_proc

        else:
            return u'Succeed:没有问题'
